import {getCookie, setCookie } from '@/utils/cookie'

const state = {
  // visitedViews: getCookie('visitedViews') || [],
  visitedViews: [
    {
      path: "/home",
      name: "home",
      title: '首页'
    }
  ],
  cachedViews: getCookie('cachedViews') || []
}

const mutations = {
  // 添加访问视图
  addVisitedView: (state, view) => {
    if (state.visitedViews.some(v => v.path === view.path)) return

    state.visitedViews.push(view)
    setCookie('visitedViews', state.visitedViews)
  },
  //  删除访问视图
  delVisitedView: (state, view) => {
    state.visitedViews.splice(view, 1)
  },
  //  删除其他访问视图
  delOthersVisitedView: (state, view) => {
    state.visitedViews = state.visitedViews.filter(item => item.name == view.name)
  },
  // 删除所有缓存视图
  delAllVisitedView: state => {
    state.cachedViews = []
  },
  // 更新访问视图 
  updateVisitedView: (state, view) => {
    for (let v of state.visitedViews) {
      if (v.path === view.path) {
        v = Object.assign(v, view)
        break
      }
    }
  }
}

const actions = {

  addVisitedView ({ commit }, view) {
    commit('addVisitedView', view)
  },
  delVisitedView ({ commit, state }, view) {
    return new Promise(resolve => {
      commit('delVisitedView', view)
      resolve([...state.visitedViews])
    })
  },
  delOthersVisitedViews ({ commit, state }, view) {
    return new Promise(resolve => {
      commit('delOthersVisitedView', view)
      resolve([...state.visitedViews])
    })
  },

  delAllViews ({ commit }) {
    commit('delAllVisitedView')
  },

  updateVisitedView ({ commit }, view) {
    commit('updateVisitedView', view)
  }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}